<template>
  <div class="rich-editor-container">
    <Toolbar
      style="border-bottom: 1px solid #eee"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="state.mode"
    />
    <Editor
      v-model="text"
      :style="{ height: state.height}"
      :defaultConfig="editorConfig"
      :mode="state.mode"
      class="editor-content"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef, onMounted, reactive, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'

const text = defineModel()

const editorRef = shallowRef() // 必须用 shallowRef

const state = reactive({
  height: '600px',
  mode: 'simple', // default 或 'simple'
})

const setSpellCheckFasle = async() => {
  let doms = await document.getElementsByClassName('w-e-scroll')
  for (let dom of doms) {
    if (dom) {
      if (dom.children.length > 0) {
        dom.children[0].setAttribute('spellcheck', 'false')
      }
    }
  }
}

onMounted(() => {
  setSpellCheckFasle()
})

const toolbarConfig: any = {}
toolbarConfig.toolbarKeys = [
  'clearStyle',
  '|',
  'bold',
  'italic',
  'through', 
  'bulletedList', 'numberedList',
  'todo',
  'codeBlock',
  'blockquote',
  'emotion',
  'color', 'bgColor',
  'headerSelect',
  'insertLink',
  'insertTable',
  // 'uploadImage',
  '|',
  'undo',
  'redo',
  // '|',
  // 'fullScreen'
]
const editorConfig = {
  // placeholder: '请输入内容...'
}

const handleCreated = (editor: any) => {
  editorRef.value = editor
}

onBeforeUnmount(() => {
  window.onresize = null
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style lang="scss" scoped>
.rich-editor-container {
  padding: 4px;
}
.editor-content {
  overflow-y: hidden;
  font-size: 15px;
  :deep(.w-e-text-container) {
    // padding: 0 15px;
  }
  :deep(p) {
    margin: 12px 0;
  }
}
</style>
